<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600"
    append-to-body
    show-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="cancelHandle"
  >
    <!-- Form -->
    <Form
      ref="formRef"
      :form="form"
      :config="config"
      :rules="rules"
      :name="name"
      label-width="80"
      width="100%"
      @change="changeHandle"
    >
      <template #inputNumber="{ data }">
        <span>{{ data.text }}</span>
      </template>
    </Form>
    <!-- Footer -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelHandle">取消</el-button>
        <el-button type="primary" @click="searchHandle">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
// components
import Form from '@/components/Form/Form.vue'
// hooks
import useDialog from '@/hooks/useDialog'
import useForm from '@/hooks/useForm'
// others
import { ref, watch } from 'vue'
import { aFormData, aFormConfig, aFormRules } from './config'

// props
const props = defineProps({
  current: {
    type: Object,
    default: () => null
  }
})
// emits
const emit = defineEmits(['confirm'])

// Dialog
const { visible, hide, show } = useDialog()
const confirm = () => {
  hide()
  emit('confirm')
}
const title = ref('')

/** Form */
const formRef = ref()
const { form, config, rules, submitForm, resetForm } = useForm({
  formRef,
  formData: aFormData,
  formConfig: aFormConfig,
  formRules: aFormRules
})
const cancelHandle = () => {
  hide()
  resetForm()
}
const searchHandle = async () => {
  submitForm(() => {
    confirm()
    resetForm()
  })
}

const changeHandle = (value, prop, item) => {
  console.log(111, value, prop, item)
}

/** 初始化 */
watch(
  () => visible.value,
  (val) => {
    if (val) {
      title.value = props.current ? '编辑分组' : '新增分组'
      form.value.name = props.current?.name || ''
      form.value.status = props.current?.status || 1
    }
  }
)

defineExpose({
  visible,
  hide,
  show
})
</script>

<style lang="less" scoped></style>
